/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import com.sun.java.swing.plaf.windows.resources.windows;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Rocker000
 */

import dao.SanPham_dao;
import java.util.Hashtable;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadBase.FileUploadIOException;
import org.apache.commons.fileupload.FileItem;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.File;
import javax.servlet.Servlet;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.omg.PortableInterceptor.LOCATION_FORWARD;
import pojo.SanPham_pojo;

public class themsanpham_controller extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    
    //không request dc parameter từ multipart/form-data  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try 
        {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            
            if(!isMultipart)
            {            
            }
            else
            {                
                //đối tượng xử lý file
                DiskFileItemFactory factory= new DiskFileItemFactory();
                //đối tượng upload file
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try
                {
                    //các object lấy được thông qua upload
                    items = upload.parseRequest(request);
                }
                catch(FileUploadException e)
                {
                    out.println("Lỗi upload file");
                }
                
                //đối tượng dùng để lấy các parameter khác không phải là file
                Hashtable params = new Hashtable();
                String filename = null;
                //Duyệt các item
                Iterator iter = items.iterator();
                while(iter.hasNext())
                {
                    FileItem item = (FileItem)iter.next();
                    //nếu là formfield(không phải multipart/form-data)
                    if(item.isFormField())
                    {
                        params.put(item.getFieldName(),item.getString());
                    }
                    //nếu là multipart/form-data (file upload)
                    else
                    {
                    //chỉ dịnh folder chua file
                    String destination = "/Image/sanpham";
                    //dường dẫn vào thư mục build/web
                    String destinationRealpath = getServletContext().getRealPath(destination);                                        
                    //đạt kích thước tối đa cho file
                    factory.setSizeThreshold(1024);
                    //đặt dường dẫn cho file
                    factory.setRepository(new File(destinationRealpath));
                    //đối tượng upload file
                    ServletFileUpload uploader = new ServletFileUpload(factory);  
                    File file = new File(destinationRealpath,item.getName());
                    try{item.write(file);}catch(Exception ex){}  
                    filename=item.getName();
                    }
                }
                String ma = (String)params.get("txtmasanpham");               
                String ten = (String)params.get("txttensanpham");
                String tensanpham = new String(ten.getBytes("ISO8859_1"),"UTF8");
                String loai = (String)params.get("cbloaisanpham");
                String hieu = (String)params.get("cbthuonghieu");
                int soluongton = Integer.parseInt((String)params.get("txtsoluongton"));
                float kichthuoc = Float.parseFloat((String)params.get("txtkichthuoc"));
                double gia = Double.parseDouble((String)params.get("txtgia"));
                String image = "Image/sanpham/"+filename;
                //String chitietkhac  = (String)params.get("txtchitiet"); 
                
                String chitietkhac = new String(String.valueOf(params.get("txtchitiet")));
                String chitietkhacutf8 = new String(chitietkhac.getBytes("ISO8859_1"),"UTF8");
                int soluotmua=0;
                
                
                SanPham_pojo sp = new SanPham_pojo();
                sp.setChiTietSanPham(chitietkhacutf8);
                sp.setGia(gia);
                sp.setHieu(hieu);
                sp.setImage(image);
                sp.setKichThuoc(kichthuoc);
                sp.setMaLoai(loai);
                sp.setMaSanPham(ma);
                sp.setSoLuongTon(soluongton);
                sp.setSoLuotMua(soluotmua);
                sp.setTenSanPham(tensanpham);
                
                
                int kq = SanPham_dao.ThemSanPham(sp);
                if(kq!=-1)                    
                    request.setAttribute("err","Thêm sản phẩm thất bại!");
                else
                {}
                response.sendRedirect("themsanpham.jsp");
            }             
        } 
        catch(Exception ex)
        {
            out.println("Lỗi!");
        }
        finally 
        {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
